import { defineStore } from 'pinia'
import { buyProduct, IProduct } from '../api/shop'
import {useProductsStore} from './product'

type CartProduct={
    quanlitity:number
}& Omit<IProduct,'inventory'>

export const useCartStore=defineStore('cart',{
    state:()=>{
        return {
            cartProducts: [] as CartProduct[],
            checkoutStatus:null as null |string
        }
    },
    getters:{
        //计算总价
        totalPrice(state){
            return state.cartProducts.reduce((total,item)=>{
                return total +item.price*item.quanlitity;
            },0)
        }
    },
    actions:{
        //加入购物车
        addProductToCart(product:IProduct){
            if(product.inventory<1){
                return
            }
            //检查购物车中是否存在该商品
            const checkItem=this.cartProducts.find(item=> item.id===product.id)
            if(checkItem){
                //如果有则数量+1
                checkItem.quanlitity++
            }else{
                this.cartProducts.push({
                    id:product.id,
                    title:product.title,
                    price:product.price,
                    quanlitity:1
                })
            }
            //更新商品的库存
            const productsStore=useProductsStore()
            //减少库存
            productsStore.decreaseProduct(product)
            console.log('state调用了',product)
        },    


        /**
         * 检查是否结算成功
         */
        async checkout() {
            const result = await buyProduct()
            this.checkoutStatus=result? '成功':'失败'
            //清空购物车
            if(result){
                this.cartProducts=[]
            }
        }
    }
})